<?php

namespace App\Http\Controllers;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Request;
use GuzzleHttp\Exception\RequestException; // 引入异常类

class PayBillController
{


    public $httpRequestUrl = "https://www.payxiao.com/payApi";

    /**
     *  获取账单码
     * @return void
     */
    public function getBillOrder(Request $request) {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '未知UA';
        file_put_contents('/www/wwwlogs/wechat_log.txt', "当前UA: {$ua}\n判断结果: " . (strpos($ua, 'MicroMessenger') !== false ? '是微信' : '不是微信') . "\n", FILE_APPEND);
        $params = http_build_query($request::query());
        $client = new Client();
        $option = ['headers' => ['Content-Type' => 'application/json;charset=UTF-8']];
        $req = $client->get($this->httpRequestUrl . "/paybill/code/sn/" . $request::query('code'), $option);
        file_put_contents('/www/wwwlogs/wechat_log.txt', "浏览器开始扫码req\n", FILE_APPEND);
        $body = json_decode($req->getBody()->getContents());
        file_put_contents('/www/wwwlogs/wechat_log.txt', "浏览器开始扫码body\n", FILE_APPEND);

        // 获取不到终端支付参数错误处理
        if ($body->code == 500) {
            return redirect($request::root() . "/mer.html");
        }
       $red = $request::root() . '/getBillpay?' .  "orderid=" . $body->data->sn . "&payAmount=" . $body->data->paidpriceDe . "&orderAmount=" . $body->data->priceDe . "&tersn=" . $body->data->tersn . "&mersn=" . $body->data->mersn;
       file_put_contents('/www/wwwlogs/wechat_log.txt', "浏览器开始扫码/getBillpay---{$red}\n", FILE_APPEND);
       return redirect($red);
    }


    public function getBillOrderss(Request $request) {
        try {
            // 修正：用实例方法获取query参数，避免静态调用
            $code = $request->query('code');
            if (empty($code)) {
                file_put_contents('/www/wwwlogs/wechat_log.txt', "错误：缺少code参数\n", FILE_APPEND);
                return redirect($request->root() . "/mer.html");
            }

            $client = new Client();
            $option = ['headers' => ['Content-Type' => 'application/json;charset=UTF-8']];
            $apiUrl = $this->httpRequestUrl . "/paybill/code/sn/" . $code;

            // 记录请求URL，确认是否正确
            file_put_contents('/www/wwwlogs/wechat_log.txt', "请求接口：{$apiUrl}\n", FILE_APPEND);

            $req = $client->get($apiUrl, $option);
            $responseBody = $req->getBody()->getContents();

            // 记录原始响应体，判断是否为有效JSON
            file_put_contents('/www/wwwlogs/wechat_log.txt', "接口响应体：{$responseBody}\n", FILE_APPEND);

            $body = json_decode($responseBody);
            // 检查JSON解析是否成功
            if (json_last_error() !== JSON_ERROR_NONE) {
                file_put_contents('/www/wwwlogs/wechat_log.txt', "JSON解析失败：" . json_last_error_msg() . "\n", FILE_APPEND);
                return redirect($request->root() . "/mer.html");
            }

            // 检查code字段是否存在
            if (!isset($body->code)) {
                file_put_contents('/www/wwwlogs/wechat_log.txt', "响应缺少code字段：" . print_r($body, true) . "\n", FILE_APPEND);
                return redirect($request->root() . "/mer.html");
            }

            // 错误处理
            if ($body->code == 500) {
                file_put_contents('/www/wwwlogs/wechat_log.txt', "接口返回500错误\n", FILE_APPEND);
                return redirect($request->root() . "/mer.html");
            }

            // 检查data字段是否存在及必要属性
            if (!isset($body->data) || !is_object($body->data)) {
                file_put_contents('/www/wwwlogs/wechat_log.txt', "响应缺少data字段或data不是对象\n", FILE_APPEND);
                return redirect($request->root() . "/mer.html");
            }
            $requiredFields = ['sn', 'paidpriceDe', 'priceDe', 'tersn', 'mersn'];
            foreach ($requiredFields as $field) {
                if (!isset($body->data->$field)) {
                    file_put_contents('/www/wwwlogs/wechat_log.txt', "data缺少必要字段：{$field}\n", FILE_APPEND);
                    return redirect($request->root() . "/mer.html");
                }
            }

            // 用http_build_query拼接URL，避免手动拼接错误
            $params = [
                'orderid' => $body->data->sn,
                'payAmount' => $body->data->paidpriceDe,
                'orderAmount' => $body->data->priceDe,
                'tersn' => $body->data->tersn,
                'mersn' => $body->data->mersn
            ];
            $red = $request->root() . '/getBillpay?' . http_build_query($params);
            file_put_contents('/www/wwwlogs/wechat_log.txt', "跳转URL：{$red}\n", FILE_APPEND);
            return redirect($red);

        } catch (RequestException $e) {
            // 捕获Guzzle请求异常（超时、连接失败等）
            $errorMsg = "请求接口失败：" . $e->getMessage() . "，请求URL：{$apiUrl}";
            file_put_contents('/www/wwwlogs/wechat_log.txt', $errorMsg . "\n", FILE_APPEND);
            return redirect($request->root() . "/mer.html");
        } catch (Exception $e) {
            // 捕获其他未知异常
            $errorMsg = "未知错误：" . $e->getMessage();
            file_put_contents('/www/wwwlogs/wechat_log.txt', $errorMsg . "\n", FILE_APPEND);
            return redirect($request->root() . "/mer.html");
        }
    }





    public function createdBillParams(Request $request)
    {
       file_put_contents('/www/wwwlogs/wechat_log.txt', "浏览器开始扫码1\n", FILE_APPEND);
       // 日志：记录入
        $params = http_build_query($request::query());
        file_put_contents('/www/wwwlogs/wechat_log.txt', "浏览器开始扫码2\n", FILE_APPEND);
        // 临时添加日志，查看判断结果
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '未知UA';
        file_put_contents('/www/wwwlogs/wechat_log.txt', "当前UA: {$ua}\n判断结果: " . (strpos($ua, 'MicroMessenger') !== false ? '是微信' : '不是微信') . "\n", FILE_APPEND);
        if(strpos($ua, 'MicroMessenger') !== false){
            $user = session('wechat.oauth_user.default'); // 拿到授权用户资料
            $params = $params . "&openid=" . $user['id'];
            file_put_contents('/www/wwwlogs/wechat_log.txt', "进入微信条件".$user['id']."\n", FILE_APPEND); // 确认是否进入
        }
        return redirect($request::root() . "/order/page/order.html?" . $params);
    }


    public function wechatCallback(Request $request)
        {
            // 从微信OAuth获取用户
            $oauth = app('wechat.oauth');
            $user = $oauth->user();

            // 存session
            session(['wechat_user' => $user]);

            file_put_contents('/www/wwwlogs/wechat_log.txt', "授权完成，openid: {$user['id']}\n", FILE_APPEND);

            // 授权后回跳到原始接口
            return redirect('/getBillpay?' . http_build_query($request->query()));
        }

  // 判断是否为微信浏览器（改用框架请求对象获取UA，避免依赖全局变量）
  public function isWechatBrowser()
  {
      // 从请求头获取User-Agent（框架方式，更规范）
      $userAgent = request()->header('User-Agent', '');
      if (empty($userAgent)) {
          return false;
      }
      return strpos(strtolower($userAgent), 'micromessenger') !== false;
  }


    /**
     * orderpay
     */
    public function orderpay(Request $request) {

      $data =  $request::query();
      $payType = 0;

      if($data['payType'] == 1004 || $data['payType'] == 1005) {
         $payType = 5;
      }


      if($data['payType'] == 1003 || $data['payType'] == 1033) {
         $payType = 2;
      }

      $client = new Client();
      $params = [
          "device_type" => 3,
          "tradeMoney" => $request::get('amount') * 100,
          "payType" => $payType,
          "sn" => $request::get('tersn'),
          "tenant_no" => $request::get('mersn'),
          'openid' => $request::get('openid') ?? null,
          'remarks' => $request::get('remark'),
          'appid' => "wxd435897cbdb1e0f8",
          'billcode_sn' => $request::get('orderid'),
      ];
      $option = ['headers' => ['Content-Type' => 'application/json;charset=UTF-8'], 'body' => json_encode($params)];
      $req = $client->post($this->httpRequestUrl . "/payweb/send", $option);
      $result = json_decode($req->getBody()->getContents());
      return $result;
    }
}
